/**
 * Copyright 2013 Qiyi Inc. All rights reserved.
 *
 * @file:   Album.Crop.js
 * @path:   js-src/album/
 * @desc:   截图用插件
 * @author: gengwei@qiyi.com
 * @date:   2013-05-10
 */

///import js-src/lib/
///import js-src/com/

(function($, undefined) {
    $.widget('ui.imagecrop', {
        version: '0.0.1',
        options: {
            'gallery': null,
            'cropimg': null,
            'results': null
        },
        $container: null,
        _jCorpObj: null,
        _scaleInUse: null,
        _create: function(options) {
            this.options = $.extend({}, this.options, options);
            this.$container = this.element;
            this._bindEvents(options);
            this.$container.data('imagecrop', this);
        },
        enable: function() {
            this.$container.find('input, button').attr('disabled', false);
            this.$container.find('div.operation').removeClass('disabled');
        },
        disable: function() {
            this.$container.find('input, button').attr('disabled', true);
            this.$container.find('div.operation').addClass('disabled');
        },
        getValue: function() {
            var $results = this.$container.find(this.options.results);
            var data = {};
            $results.find('button').each(function(index, element) {
                var $button = $(this);
                var width = $button.data('width');
                var height = $button.data('height');
                var imgsrc = $button.data('imgsrc');
                var coord = $button.data('coord');
                if (imgsrc && coord) {
                    data[width + '-' + height] = {
                        index: index,
                        imgsrc: imgsrc,
                        spath: $button.data('spath'),
                        w: width,
                        h: height,
                        x1: Math.floor(coord.x),
                        y1: Math.floor(coord.y),
                        x2: Math.floor(coord.x2),
                        y2: Math.floor(coord.y2),
                        data: $button.data('data') || {}
                    };
                }
            });
            return data;
        },
        setValue: function(value) {
            var that = this;
            var $results = this.$container.find(this.options.results);
            var $gallery = this.$container.find(this.options.gallery);
            var findImage = function(imgsrc) {
                var $image = null;
                $gallery.find('img').each(function(index, element) {
                    if (imgsrc == $(this).attr('src')) {
                        $image = $(this);
                    }
                });
                return $image;
            };
            $results.find('button').each(function(index, element) {
                var $button = $(this);
                var width = $button.data('width');
                var height = $button.data('height');
                var data = value[width + '-' + height];
                var coord, imgsrc, $image;
                if (!data && !$image) {
                    return;
                }
                imgsrc = data.imgsrc;
                $image = findImage(imgsrc);
                coord = {
                    x: data.x1,
                    y: data.y1,
                    x2: data.x2,
                    y2: data.y2,
                    w: data.x2 - data.x1,
                    h: data.y2 - data.y1
                };
                $button.find('.preview').empty().html('<img src="' + imgsrc + '" />');
                $button.data('imgsrc', imgsrc);
                $button.data('coord', coord);
                $button.data('spath', data.spath);
                $button.data('data', data.data);
                if ($image) {
                    that._updateCoord.call(that, coord, $button, $image.data('width'), $image.data('height'));
                }
            });
        },
        addImages: function(images, callback) {
            var $gallery = this.$container.find(this.options.gallery);
            var gallery = this.$container.find('.slideshow').data('gallery');
            var oldTotal;
            var total = images.length;
            var afterImageLoad = function() {
                total--;
                if (0 === total) {
                    if (callback) {
                        callback();
                    }
                }
            };
            $.each(images, function(index, image) {
                var $imgdiv, data;
                data = {
                    imgsrc: image.url
                };
                if (image.shot) {
                    // 视频截图
                    data.type = 1;
                    data.area = image.area;
                } else {
                    // 数据回填    
                    data.spath = image.spath;
                    data.type = 0;
                    data.data = image.data;
                }
                $imgdiv = $('<img src="' + data.imgsrc + '">');
                $imgdiv.data(data).load(function(e) {
                    Com.Image.procThumbnail($(this), 128, 80);
                    afterImageLoad();
                }).error(function(e) {
                    afterImageLoad();
                });
                $gallery.append($('<li style="position:relative" class="item" />').append($imgdiv));
            });
            oldTotal = gallery.totalItems;
            gallery.update();
            gallery.scrollTo(oldTotal);
        },
        // 计算初始截图位置
        _calcInitCoord: function(origWidth, origHeight, scaleWidth, scaleHeight) {
            var left, top;
            var newWidth = origWidth * 2 / 3;
            var newHeight = newWidth * scaleHeight / scaleWidth;
            if (newHeight > origHeight) {
                newHeight = origHeight;
                newWidth = newHeight * scaleWidth / scaleHeight;
            }
            newWidth = Math.floor(newWidth);
            newHeight = Math.floor(newHeight);
            left = Math.floor((origWidth - newWidth) / 2);
            top = Math.floor((origHeight - newHeight) / 2);
            return {
                x: left,
                y: top,
                x2: left + newWidth,
                y2: top + newHeight
            };
        },
        // 选择一个比例
        _selectScale: function($button) {
            var imgsrc = $button.data('imgsrc');
            var coord = $button.data('coord');
            $button.data('inuse', true);
            this._scaleInUse = {
                width: $button.data('width'),
                height: $button.data('height'),
                button: $button,
                imgsrc: imgsrc,
                coord: coord
            };
            if (imgsrc && coord) {
                // if is already cropped...
                this._selectOrigImg(imgsrc);
            } else {
                this._selectOrigImg(imgsrc);
            }
        },
        // 选择一个原始图
        _selectOrigImg: function(imgsrc) {
            var $gallery = this.$container.find(this.options.gallery);
            var $cropimg = this.$container.find(this.options.cropimg);
            $image = $gallery.find('img').filter(function(index, element) {
                return $(this).attr('src') == imgsrc;
            });
            if ($image.length > 0) {
                $image.click();
            } else if (1 == $gallery.find('img').length) {
                $gallery.find('img').eq(0).click();
            } else {
                $gallery.find('li').removeClass('active');
                $cropimg.empty();
            }
        },
        // 设置 jCorp 对象
        _setupJCorp: function($image, updateCoords, scaleInUse, coord) {
            var that = this;
            if (this._jCorpObj) {
                this._jCorpObj.destroy();
            }
            this._jCorpObj = null;
            $image.Jcrop({
                keySupport: false,
                onSelect: updateCoords,
                onChange: updateCoords,
                aspectRatio: scaleInUse.width / scaleInUse.height,
                trueSize: [$image.data('width'), $image.data('height')]
            }, function() {
                that._jCorpObj = this;
                that._jCorpObj.animateTo([coord.x, coord.y, coord.x2, coord.y2]);
            });
        },
        // 绑定事件
        _bindEvents: function() {
            var that = this;
            var $gallery = this.$container.find(this.options.gallery);
            var $cropimg = this.$container.find(this.options.cropimg);
            var $results = this.$container.find(this.options.results);
            var $confirm = this.$container.find(this.options.confirm);
            // 选择裁剪比例
            $results.delegate('a', 'click', function(e) {
                e.preventDefault();
            });
            $results.delegate('button', 'click', function(e) {
                var $button = $(this);
                $button.siblings().removeClass('active');
                $button.addClass('active');
                that._selectScale($(this));
            });
            // 缩略图的点击事件
            $gallery.delegate('img', 'click', function(e) {
                var $thumbimg = $(this),
                    $imgToCrop, $button;
                var t, scaleWidth, scaleHeight, imageWidth, imageHeight, cropWidth, cropHeight;
                var imgsrc = $thumbimg.attr('src'),
                    coord;
                var scaleInUse = that._scaleInUse;
                // test if is possible to do this action
                if ($thumbimg.parents('div.operation').hasClass('disabled')) {
                    return;
                }
                if (null === scaleInUse) {
                    alert('请先选择缩略图的比例');
                    return false;
                }
                if (true === $thumbimg.data('loading')) {
                    alert('该图片现在暂时不可用，请等待上传完成');
                    return false;
                }
                // get current scale button
                $button = scaleInUse.button;
                imageWidth = $thumbimg.data('width');
                imageHeight = $thumbimg.data('height');
                coord = $button.data('coord');
                // add style to selected image
                $gallery.find('li').removeClass('active');
                $thumbimg.parent().addClass('active');
                // set corp area style and set image to crop area
                cropWidth = $cropimg.outerWidth() - 2;
                cropHeight = $cropimg.outerHeight() - 2;
                t = Com.Image.resizeInside($thumbimg, cropWidth, cropHeight);
                $imgToCrop = $('<img src="' + imgsrc + '" width="' + t.width + '" height="' + t.height + '">');
                $imgToCrop.data('width', imageWidth).data('height', imageHeight).data('spath', $thumbimg.data('spath'));
                $cropimg.css({
                    width: t.width,
                    height: t.height,
                    padding: t.top + 'px ' + (cropWidth - t.width - t.left) + 'px ' + (cropHeight - t.height - t.top) + 'px ' + t.left + 'px'
                });
                $cropimg.empty().append($imgToCrop);
                //
                if (scaleInUse.imgsrc != imgsrc) {
                    coord = that._calcInitCoord(imageWidth, imageHeight, scaleInUse.width, scaleInUse.height);
                }
                // set JCrop
                $button.data('imgsrc', imgsrc);
                $button.data('spath', $thumbimg.data('spath') || null);
                $button.find('.preview').empty().html('<img src="' + imgsrc + '" />');
                that._setupJCorp($imgToCrop, function(coord) {
                    that._updateCoord.call(that, coord, $button, imageWidth, imageHeight, true);
                }, scaleInUse, coord);
            });
        },
        _updateCoord: function(coord, $button, imageWidth, imageHeight, flush) {
            var scale = coord.h / $button.find('.preview').height();
            var newWidth = Math.floor(imageWidth / scale);
            var newHeight = Math.floor(imageHeight / scale);
            var left = Math.floor(coord.x / scale);
            var top = Math.floor(coord.y / scale);
            if (flush) {
                $button.data('data', null);
            }
            $button.data('coord', coord);
            $button.find('.preview img').css({
                width: newWidth,
                height: newHeight,
                marginTop: 0 - top,
                marginLeft: 0 - left
            });
        }
    });
    $.extend($.ui.imagecrop, {
        uuid: 0,
        _isShow: false
    });
}(jQuery));